<?php
/**
 * 用户模型
 * 
 * ============================================================================
 * 版权所有: (c) 2009-2011，<UEShop Inc>，并保留所有权利。
 * 网站地址: http://www.ueshop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用；
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 *
 * @author      cmpan
 * @copyright   Copyright (c) 2009-2010 UEShop Inc. (http://www.ueshop.cn)
 * @license     http://www.ueshop.cn/1_0.txt
 */
class UserModel extends UE_Model {
    public $table  = 'ue_user';
	public $key    = 'user_id';
	
	/**
	 * 添加用户
	 *
	 * @param array $user
	 * @return bool
	 */
	public function add($user) {
	    if(empty($user['user_name']) || empty($user['user_pass'])) {
	    	$this->setErr('用户名、密码不能为空');
	    	return false;
	    }
	    
	    if (strlen($user['user_pass']) < 6) {
			$this->setErr('密码长度不能小于6位。');
			return false;
		}
	    
	    // 只有超级管理员才能添加超级用户
	    if ($_SESSION['user_type'] != 'super') {
	    	if($user['user_type'] == 'super') $user['user_type'] = 'admin';
	    }
	    
	    // 用户名不能重复
	    if (!empty($user['user_name'])) {
	    	if ($this->isUserNameReg($user['user_name'])) {
	    		$this->setErr('该用户名已经被使用');
	    		return false;
	    	}
	    }
	    
	    // Email不能重复
	    if (!empty($user['user_email'])) {
	    	if ($this->isEmailReg($user['user_email'])) {
	    		$this->setErr('该邮箱已经被使用');
	    		return false;
	    	}
	    }

		if (!empty($user['admin_role'])) {
			$user['user_role'] = join(',', $user['admin_role']);
		}
		
		$user['user_reg_dateline'] = time();
		$user['user_salt'] = substr(makeUeid(), -6);
		$user['user_pass'] = md5($user['user_pass'].$user['user_salt']);
		
		
	    return parent::add($user);
	}
	
	/**
	 * 更新用户
	 *
	 * @param array $user
	 * @return bool
	 */	
	public function update($user) {	    
		if (!empty($user['admin_role'])) {
			$user['user_role'] = join(',', $user['admin_role']);
		} else {
			$user['user_role'] = '';
		}
		
		$superId = cfg('super_admin_id');
			    		
		if ($superId == $this->id) {
			// 不允许他人修改系统创建者信息
			if ($_SESSION['user_id'] != $this->id) {
				$this->setErr('你没有权限修改该账户。');
				return false;
			} else {
				// 系统创建者的管理员类型不能被改变
				unset($user['user_type']);
				unset($user['user_role']);
			}
		}
		
	    // Email不能重复
	    if (!empty($user['user_email'])) {
	    	$regEmailUId = $this->isEmailReg($user['user_email']);
	    	if ($regEmailUId && $regEmailUId != $this->id) {
	    		$this->setErr('该邮箱已经被使用');
	    		return false;
	    	}
	    }
	    
		if (!empty($user['user_pass'])) {
			if (strlen($user['user_pass']) < 6) {
				$this->setErr('密码长度不能小于6位。');
				return false;
			}
			
			$user['user_salt'] = substr(makeUeid(), -6);
			$user['user_pass'] = md5($user['user_pass'].$user['user_salt']);
		} else {
			unset($user['user_pass']);
		}
		
	    // 只有超级管理员才能设置用户角色和修改用户类型	    
	    if ($_SESSION['user_type'] != 'super') {
	    	unset($user['user_type']);
			unset($user['user_role']);
	    }

	    // 用户名不能修改
	    unset($user['user_name']);
	    //print_r($user);
	    return parent::update($user);
	}
	
	/**
	 * Email是否已经被注册
	 *
	 * @param string $email
	 * @return int
	 */
	public static function isEmailReg($email) {
    	$sql = "SELECT user_id FROM {$this->table} WHERE user_email='$email' LIMIT 1";
    	return $this->_db()->getfirstField($sql);
	}
	
	/**
	 * Email是否已经被注册
	 *
	 * @param string $email
	 * @return int
	 */
	public static function isUserNameReg($userName) {
    	$sql = "SELECT user_id FROM {$this->table} WHERE user_name='$userName' LIMIT 1";
    	return $this->_db()->getfirstField($sql);
	}
	
	/**
	 * 删除用户
	 *
	 * @return bool
	 */
	public function delete() {
		// 不能删除超级系统创建者
		$superId = cfg('super_admin_id');
		if ($this->id == $superId) {
			return false;
		}
		
		return parent::delete();
	}
	
	/**
	 * 用户登录
	 *
	 * @param string $userAccount
	 * @param string $password
	 * @return bool
	 */
	public function login($userAccount, $password) {		
		// 用户已登录
		if ($this->hasLogin()) {
			header('Location: ' . UE::context());
			return false;
		}
		
		// 登录用户名或密码不能为空
		if (!$userAccount || !$password) {
			$this->setErr('登录账号或密码不能为空。');
			return false;
		}
		
		if (strlen($password) < 6) {
			$this->setErr('密码错误。');
			return false;
		}
		
		// 获取登录用户信息
		$userInfo = array();  
		if (cfg('account_key') == 'user_name') {
			$userInfo = $this->getUserByName($userAccount);
		} else {
			$userInfo = $this->getUserByEmail($userAccount);
		}
		
		// 用户不存在
		if (empty($userInfo)) {
			$this->setErr('用户不存在。');
			return false;
		}
		
		// 验证密码
		$passwordHash = md5($password.$userInfo['user_salt']);
		if ($passwordHash != $userInfo['user_pass']) {
			$this->setErr('密码错误。');
			return false;
		}
		
		$this->setLoginInfo($userInfo);
		return true;
	}

	
	/**
	 * 登录成功后设置的信息
	 *
	 * @param array $userInfo 登录用户的信息
	 */
	public function setLoginInfo($userInfo) {
		$_SESSION['user_id']        = $userInfo['user_id'];
		$_SESSION['user_name']      = $userInfo['user_name'];
		$_SESSION['user_pass']      = $userInfo['user_pass'];
		$_SESSION['user_type']      = $userInfo['user_type'];
		$_SESSION['user_role']      = $userInfo['user_role'];  // 注册会员使用，管理员不用
		$_SESSION['user_email']     = $userInfo['user_email'];
		$_SESSION['user_realname']  = $userInfo['user_realname'];
		$_SESSION['user_locale']    = $userInfo['user_locale'];
		$_SESSION['user_salt']      = $userInfo['user_salt'];
		$_SESSION['user_ip']        = UE_IP::realIp();
	}
	
	/**
	 * 通过用户名获取用户信息
	 *
	 * @param string $userName
	 * @return array
	 */
	public function getUserByName($userName) {
		if ($userName == 'guest') {
			return array();
		}
		
		$sql = "SELECT * FROM ue_user WHERE user_name = '$userName' LIMIT 1";
		$userInfo = UE_DB::factory()->getOne($sql);
		return $userInfo;
	}
	
	/**
	 * 通过Email获取用户信息
	 *
	 * @param string $email
	 * @return array
	 */
	public function getUserByEmail($email) {
		if (empty($email)) {
			return array();
		}
		$sql = "SELECT * FROM ue_user WHERE user_email = '$email' LIMIT 1";
		$userInfo = UE_DB::factory()->getOne($sql);
		return $userInfo;
	}
	
	/**
	 * 用户是否已登录
	 *
	 * @return bool
	 */
	public function hasLogin() {		
		if (empty($_SESSION['user_id'])) {
			return false;
		}
		
		return true;
	}
	
	/**
	 * 用户登出、注销
	 *
	 * @return bool
	 */
	public function logout() {
		session_destroy();
		$_SESSION = array();
		setcookie(cfg('auth_cookie_key'), '', time() - 3600);
				
		// TODO 单点登录注销
		return true;
	}
	
	public function adminLogin($password) {
		if (!$this->isAdmin()) {
			$this->setErr(lang('permissionDenied'));
			return false;
		}
		
		if (md5($password . $_SESSION['user_salt']) == $_SESSION['user_pass']) {
			return true;
		}
		
		return false;
	}
	
	public function isAdmin() {
		if (empty($_SESSION['user_type'])) {
			return false;
		}
		
		if (($_SESSION['user_type'] == 'admin' || $_SESSION['user_type'] == 'super')) {
			return true;
		}
		
		return false;
	}
}